package boofbridgeimaj.image.util;

import boofcv.struct.image.ImageBase;
import boofcv.struct.image.ImageFloat32;
import boofcv.struct.image.MultiSpectral;
import org.openimaj.image.FImage;
import org.openimaj.image.MBFImage;
import org.openimaj.image.MultiBandImage;
import org.openimaj.image.SingleBandImage;

/**
 * Class for converting or wrapping BoofCV data types into OpenIMAJ data types.
 *
 * @author Peter Abeles
 */
public class BoofToImaj {

	/**
	 * Converts a {@link MultiSpectral} from BoofCV into {@link MBFImage} in OpenIMAJ.
	 *
	 * @param input MultiSpectral image which is to be converted.
	 * @param output (Optional) Storage for MBFImage.  If null a new instance will be created.
	 * @return Image in an OpenIMAJ image.
	 */
	public static MBFImage convert( MultiSpectral<ImageFloat32> input , MBFImage output )
	{
		if( output == null ) {
			output = new MBFImage(input.width,input.height,input.getNumBands());
		} else {
			checkCompatible(input, output);
		}

		for( int i = 0; i < input.getNumBands(); i++ )
			convert(input.getBand(i),output.getBand(i));

		return output;
	}

	/**
	 * Converts a {@link ImageFloat32} from BoofCV into {@link FImage} in OpenIMAJ.
	 *
	 * @param input ImageFloat32 image which is to be converted.
	 * @param output (Optional) Storage for FImage.  If null a new instance will be created.
	 * @return Image in an OpenIMAJ image.
	 */
	public static FImage convert( ImageFloat32 input , FImage output ) {
		if( output == null ) {
			output = new FImage(input.width,input.height);
		} else {
			checkCompatible(input, output);
		}

		int srcIndex = 0;
		for (int y = 0; y < input.height; y++)
			for (int x = 0; x < input.width; x++)
				output.pixels[y][x] = input.data[srcIndex++];

		return output;
	}

	public static void checkCompatible(MultiSpectral a, MultiBandImage b) {
		if( a.getWidth() != b.getWidth() || a.getHeight() != b.getHeight() )
			throw new IllegalArgumentException("Input images do not have equivalent shapes");
		if( a.getNumBands() != b.numBands() )
			throw new IllegalArgumentException("Input images do not have the same number of bands");
	}

	public static void checkCompatible(ImageBase a, SingleBandImage b) {
		if( a.getWidth() != b.getWidth() || a.getHeight() != b.getHeight() )
			throw new IllegalArgumentException("Input images do not have equivalent shapes");
	}
}
